package com.woniu.woniu_bx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.woniu.woniu_bx.mapper.*;
import com.woniu.woniu_bx.pojo.*;
import com.woniu.woniu_bx.service.GoodsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author : 王泰元
 * @className: GoodsServiceImpl
 * @description: TODO
 * @date : 2022/8/27 16:23
 */
@Transactional
@Service
@Slf4j
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsImgMapper goodsImgMapper;

    @Autowired
    private GoodsCommentMapper goodsCommentMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private GoodsCategoryMapper goodsCategoryMapper;

    //多条件查询
    @Override
    public PageBean<Goods> getByPage(Goods goods, Integer pageNum, Integer pageSize) {
        PageBean<Goods> pageBean = new PageBean<>();
        Page<Object> page = PageHelper.startPage(pageNum, pageSize);
        List<Goods> goodsList = goodsMapper.getByCondition(goods);

        pageBean.setCurrPage(pageNum);
        pageBean.setData(goodsList);
        pageBean.setCurrPageSize(goodsList.size());
        pageBean.setPageSize(pageSize);
        pageBean.setTotalPages(page.getPages());
        pageBean.setTotalNums((int) page.getTotal());
        return pageBean;
    }

    @Override
    public void updateByCondition(Goods goods) {
        if (goods.getId() == null) {
            throw new NullPointerException("id不能为空");
        }
        goodsMapper.update(goods);
    }

    @Override
    public void updateStatus(Integer id, String status) {
        goodsMapper.updateStatus(id, status);
    }


    /**
     * @return void
     * @Description 商品新增（包括商品图片的新增）
     * @Date 17:46 2022/8/29
     * @Author 魏才林
     * @Param [goods]
     **/
    @Override
    public void add(Goods goods) {
        //设置初始值
        goods.setSaleNum(0);//初始销量为0
        goods.setStatus("c");//初始状态为：c -> 审核中；  审核未通过(n)、审核通过(y)、下架(d)、审核中(c)

        //（1）先把商品新增，新增后获得自增id
        goodsMapper.insert(goods);

        //（2）根据（1）中自增的商品id，对商品图片进行批量新增
        goods.getGoodsImgs().forEach(img -> {
            img.setRelationalId(goods.getId());
        });
        goodsImgMapper.insert(goods.getGoodsImgs());
    }

    /**
     * @return void
     * @Description 删除商品（商品逻辑删除、商品图片物理删除）
     * @Date 9:55 2022/8/30
     * @Author 魏才林
     * @Param [id]
     **/
    @Override
    public void delete(Integer id) {
        //先获取完整的商品信息(出了商品图片)
        Goods goods = goodsMapper.selectById(id);

        //商品改为逻辑删除，d -> 下架；  未审核(n)、审核通过(y)、下架(d)、驳回(r)
        goods.setStatus("d");
        goodsMapper.updateById(goods);

        //TODO 可以讨论下业务中，客户在发布商品时，是不是必须要上传至少一张以上的图片，
        // 然后这里删除的时候就可以做判断，没图片的时候就不删除，有图片就要删除
        // 这里默认情况：用户发布商品时必须要上传图片

        //获取商品图片，进行批量删除
        List<Img> imgs = goodsImgMapper.getAllImgByGoodsId(goods.getId());
        List<Integer> ids = new ArrayList<>();
        imgs.forEach(i -> {
            ids.add(i.getId());
        });
        goodsImgMapper.delete(ids, imgs.get(0).getRelationalId());
    }

    /**
     * @return void
     * @Description 更新商品（包括对应的商品图片）
     * @Date 10:11 2022/8/30
     * @Author 魏才林
     * @Param [goods]
     **/
    @Override
    public void update(Goods goods) {
        //重新提交编辑后应再次进入待审核状态
        goods.setStatus("c");
        //对商品进行更新
        goodsMapper.updateById(goods);

        //TODO 可以讨论下业务中，客户在发布商品时，是不是必须要上传至少一张以上的图片，
        // 然后这里更新的时候就可以做判断，没图片的时候就不删除，有图片就要删除
        // 这里默认情况：用户发布商品时必须要上传图片

        // 更新商品图片（先获取原商品图片进行删除，在把新的商品图片进行新增）
        // 获取旧商品图片，进行批量删除
        List<Img> imgs = goodsImgMapper.getAllImgByGoodsId(goods.getId());
        List<Integer> ids = new ArrayList<>();
        imgs.forEach(i -> {
            ids.add(i.getId());
        });
        goodsImgMapper.delete(ids, goods.getId());

        // 获取新商品图片，进行批量新增
        goodsImgMapper.insert(goods.getGoodsImgs());
    }


    /**
     * 根据商品id查商品，带出商品图片、商品评论、计算评分
     *
     * @param id 商品id
     * @return Goods
     */
    @Override
    public Goods getGoodsById(Integer id) {
        Goods goods = goodsMapper.selectById(id);
        //得到该商品的类别
        goods.setGoodsCategory(goodsCategoryMapper.findCategoryById(goods.getCategoryId()));

        // 商品图片集合
        goods.setGoodsImgs(goodsImgMapper.getAllImgByGoodsId(goods.getId()));

        // 得到商品评论集合
        List<GoodsComment> goodsComments = goodsCommentMapper.getByGoodsId(id);
        goods.setGoodsComments(goodsComments);

        // 获取发布用户信息
        User user = userMapper.selectById(goods.getUserId());
        user.setUserImages(userMapper.getUserImagesById(user.getId()));
        goods.setUser(user);

        // 计算总评分
        BigDecimal totalScore = new BigDecimal("0");
        for (GoodsComment comment : goodsComments) {
            totalScore = totalScore.add(new BigDecimal(comment.getScore()));
        }
        log.debug("总评分 totalScore: {}", totalScore);
        // 判断总评分是否为0
        if(totalScore.compareTo(BigDecimal.ZERO)!=0){
            // 得到平均分，保留一位小数，四舍五入
            BigDecimal goodsScore = totalScore.divide(new BigDecimal(goodsComments.size()),1, BigDecimal.ROUND_HALF_UP);
            log.debug("商品评分 goodsScore: {}", goodsScore);

            goods.setGoodsScore(goodsScore);
        }else{
            goods.setGoodsScore(BigDecimal.ZERO);
        }

        return goods;
    }

    /**
     * @return void
     * @Description 获取陪玩的所有商品信息（未被逻辑删除）
     * @Date 10:30 2022/8/30
     * @Author 魏才林
     * @Param [userId, pageNum, pageSize]
     **/
    @Override
    public PageBean<Goods> getAllGoodsNoDelByUserId(Integer userId, Integer pageNum, Integer pageSize) {
        //条件包装类
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        //注意：这里的第一个参数，是数据库的列名
        wrapper.eq("user_id", userId);
        wrapper.eq("status", "d");  // d -> 下架；  未审核(n)、审核通过(y)、下架(d)、驳回(r)

        Page page = PageHelper.startPage(pageNum, pageSize);
        //获取所有商品
        List<Goods> allGoods = goodsMapper.selectList(wrapper);

        PageBean<Goods> goodsPageBean = new PageBean<>();
        goodsPageBean.setPageSize(pageSize);
        goodsPageBean.setData(allGoods);
        goodsPageBean.setCurrPage(pageNum);
        goodsPageBean.setCurrPageSize(allGoods.size());
        goodsPageBean.setTotalPages(page.getPages());
        goodsPageBean.setTotalNums((int) page.getTotal());


        //循环给所有商品，去查询出各自的商品图片
        allGoods.forEach(g -> {
            g.setGoodsImgs(goodsImgMapper.getAllImgByGoodsId(g.getId()));
        });

        return goodsPageBean;
    }

    /**
     * @return void
     * @Description 获取陪玩的所有商品信息（包括被逻辑删除的）
     * @Date 10:20 2022/8/30
     * @Author 魏才林
     * @Param [userId, pageNum, pageSize]
     **/
    @Override
    public PageBean<Goods> getAllGoodsByUserId(Integer userId, Integer pageNum, Integer pageSize) {
        //条件包装类
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        //注意：这里的第一个参数，是数据库的列名
        wrapper.eq("user_id", userId);

        Page page = PageHelper.startPage(pageNum, pageSize);
        //获取所有商品
        List<Goods> allGoods = goodsMapper.selectList(wrapper);

        PageBean<Goods> goodsPageBean = new PageBean<>();
        goodsPageBean.setPageSize(pageSize);
        goodsPageBean.setData(allGoods);
        goodsPageBean.setCurrPage(pageNum);
        goodsPageBean.setCurrPageSize(allGoods.size());
        goodsPageBean.setTotalPages(page.getPages());
        goodsPageBean.setTotalNums((int) page.getTotal());


        //循环给所有商品，去查询出各自的商品图片
        allGoods.forEach(g -> {
            g.setGoodsImgs(goodsImgMapper.getAllImgByGoodsId(g.getId()));
        });

        return goodsPageBean;
    }

    @Override
    public Goods getCategoryNameByid(int id) {
        return goodsMapper.findCategoryById(id);
    }

    @Override
    public List<String> getGoodsImagesById(Integer id) {
        return goodsMapper.getGoodsImagesById(id);
    }

    /**
     * 根据类别 id，查询出商品，带出用户信息
     * @param categoryId 类别 id
     * @return 商品集合
     */
    @Override
    public List<Goods> getByCategoryId(Integer categoryId){
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", categoryId);
        List<Goods> goodsList = goodsMapper.selectList(queryWrapper);
        for (Goods goods : goodsList) {
            User user = userMapper.selectById(goods.getUserId());
            goods.setUser(user);
        }
        return goodsList;
    }

    @Override
    public List<Goods> getByGenderAndCategoryId(Integer categoryId,String gender) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", categoryId);
        List<Goods> goodsList = goodsMapper.selectList(queryWrapper);
        for (int i=0;i<goodsList.size();i++) {
            Goods goods = goodsList.get(i);
            User user = userMapper.selectById(goods.getUserId());
            goods.setUser(user);
            if(!user.getGender().equals(gender)){
                goodsList.remove(goods);
                i--;
            }
        }
        return goodsList;
    }

    @Override
    public List<Goods> findByRandom() {
        return goodsMapper.findByRandom();
    }

    @Override
    public List<Goods> getGoodsListByUserId(Integer userId) {
        List<Goods> goodsList = goodsMapper.getGoodsListByUserId(userId);
        return goodsList;
    }

    @Override
    public List<Goods> getGoodsListByUserIdAndStatus(Integer userId,String status) {
        List<Goods> goodsList = goodsMapper.getGoodsListByUserIdAndStatus(userId,status);
        return goodsList;
    }
}
